<?php
namespace app\admin\controller;

use app\admin\model\Applet as AppletModel;
use app\admin\model\User as UserModel;
use app\admin\model\Record as RecordModel;
use app\admin\model\Device as DeviceModel;
use app\admin\model\Wechat as WechatModel;
use think\facade\View;
use hema\wechat\Driver;
use think\facade\Cache;

/**
 * 商户后台首页
 */
class Index extends Controller
{
    
    public function index()
    {
    	$count = array();
		$count['applet'] = AppletModel::getCount();		//小程序
		$count['user'] = UserModel::getCount();	//用户统计
        $count['record'] = RecordModel::getCount();
        $count['wechat'] = WechatModel::count();   //云设备统计
		$count['device'] = DeviceModel::count();	//云设备统计
        return View::fetch('index', compact('count'));
    }

    public function fans()
    {
    	$wx = new Driver;
    	if(!$data = Cache::get('fans_user')){
    		$res = $wx->getFans(0);
    		$data = $res['data']['openid'];
    		Cache::set('fans_user',$data);
    	}
    	if(!$n = Cache::get('user_n')){
    		$n = 0;
    	}
    	//查询是否存在
    	if(!UserModel::getUser(['open_id' => $data[$n]])){
    		//添加纪录
	    	$user = $wx->getWechatUserInfo($data[$n],0);
	    	$user['user_name'] = time();
	    	$user['password'] = hema_hash('123456');
	    	$user['is_subscribe'] = 1;
	    	$model = new UserModel;
	    	if($model->save($user)){
	    		$n = $n+1;
	    		Cache::set('user_n',$n);
	    		echo "----------- OK --------------".$n;
	    	}else{
	    		echo "********************";
	    	}
    	}else{
    		$n = $n+1;
	    	Cache::set('user_n',$n);
    		echo "用户已存在".$n;
    	}
    	//return redirect(url('index/fans'));
    }

}
